

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>头盔检测系统-数据分析</title>
    <link rel="stylesheet" type="text/css" href="EasyUI/themes/default/easyui.css">
    <link rel="stylesheet" type="text/css" href="EasyUI/themes/icon.css">
    <link rel="stylesheet" type="text/css" href="EasyUI/themes/color.css">
    <link rel="stylesheet" type="text/css" href="EasyUI/demo.css">
    <script type="text/javascript" src="EasyUI/jquery.min.js"></script>
    <script type="text/javascript" src="EasyUI/jquery.easyui.min.js"></script>
    <script src="helmet.js"></script>
    <script src="chart.js"></script>
    <style>
        /* 图表容器样式 - 使用Flexbox水平排列 */
        .charts-container {
            display: flex;
            justify-content: space-around;
            max-width: 1500px;
        }

    </style>
</head>
<body class="easyui-layout" style="background: #00bbee;">
<div style="padding: 20px;">
    <div style="text-align: left; font-size: 12px;">欢迎 <span id="userNameForWelcome">用户名</span> </div>
    <div id="select" data-options="region:'center',border:false" style="background: #00bbee; text-align: left; margin-top: 50px;">
        <label for="selectForm" style="font-size: 20px">选择摄像头：</label>
        <form id="selectForm" >
            <label for="province">省：</label>
            <select id="province" style="width: 150px " class="easyui-combobox" data-options="
url:'popedom/getProvinces',
valueField:'id',
textField:'name',
onSelect:function(record){
$('#city').combobox('reload','popedom/getCitiesByProvinceId?provinceId='+record.id);
}">
            </select>
            <label for="city">市：</label>
            <select id="city" style="width: 150px " class="easyui-combobox" data-options="
valueField:'id',
textField:'name',
onSelect:function(record){
$('#district').combobox('reload','popedom/getDistrictsByCityId?cityId='+record.id);
}">
            </select>
            <label for="district">区：</label>
            <select id="district" style="width: 150px " class="easyui-combobox" data-options="
valueField:'id',
textField:'name',
onSelect:function(record){
$('#block').combobox('reload','popedom/getBlocksByDistrictId?districtId='+record.id);
}">
            </select>
            <label for="block">块：</label>
            <select id="block" style="width: 150px " class="easyui-combobox" data-options="
valueField:'id',
textField:'name',
onSelect: function(){getCameras()}">
            </select>
            <label for="camera">已选摄像头：</label>
            <select id="camera" class="easyui-combobox" multiple="true" multiline="true"
                    style="width:150px;height:100px;" data-options="
valueField:'id',
textField:'id'">
            </select>
        </form>

        <!-- 新增一个包裹容器，使用Flex布局 -->
        <div style="display: flex; align-items: flex-start; gap: 20px; padding: 20px;">
            <!-- 原selectDateBox -->
            <div id="selectDateBox" style="flex: 1; max-width: 300px; padding: 30px 60px; ">
                <label for="startTime">选择开始时间：</label>
                <input id="startTime" class="easyui-datetimebox" data-options="required:true" style="width:100%;">
                <label for="endTime">选择结束时间：</label>
                <input id="endTime" class="easyui-datetimebox" data-options="required:true" style="width:100%;">
            </div>

            <!-- 原analyseButton -->
            <div id="analyseButton" style="flex: 1; max-width: 300px; padding: 30px 60px; display: flex; align-items: center; justify-content: center; ">
                <button type="button" onclick="analyse()" style="padding: 10px 20px;">开始统计</button>
            </div>
        </div>

    </div>
    <!-- 图表容器 -->
    <div class="charts-container">
        <!-- 柱状图 -->
        <div class="barChart-wrapper" style="width: 600px; height: 400px;">
            <canvas id="dayBarChart"></canvas>
        </div>
        <div class="barChart-wrapper" style="width: 500px; height: 400px;">
            <canvas id="cameraBarChart"></canvas>
        </div>
        <!-- 饼状图 -->
        <div class="pieChart-wrapper" style="width: 300px; height: 300px;">
            <canvas id="pieChart"></canvas>
        </div>
    </div>
</div>
<div id="print" data-options="region:'east',split:true,width:300" style="padding: 10px;">
    <form style="height: 80%; width: 100%">
        <label for="outputBox" >识别结果：</label>
        <textarea id="outputBox" style="height: 100%; width: 100%"></textarea>
    </form>
    <div style="text-align: right; position: absolute; bottom: 40px; right: 40px;">
        <button type="button" onclick="exitSystem()">退出系统</button>
    </div>
</div>

</body>
<script>
    //页面加载
    $(document).ready(function() {
        welcome().then(user => {
//console.log(user)
            if (user) {
                checkFunc(user.func);
                document.getElementById('userNameForWelcome').innerText = user.name;
                initCameraList(user);
//initDefaultPopedom(user);
// //示例数据
// const startDate = new Date('2023-01-01');
// const dailyData = [12, 4, 19, 3, 5, 8, 14, 7, 9, 11, 6, 4, 19, 3, 5, 8
// , 19, 3, 5, 8, 14, 7, 9, 11, 6, 4, 19, 3, 5, 8, 14, 7, 9, 11, 6, 4, 19, 3, 5, 8]; // 长度可变
// const t = [1,2,3,4,5,6,7,8,9];
// // 调用函数
// dayBarChart(startDate, dailyData);
// cameraBarChart(t,t)
// pieChart();
            }
            else
                exitSystem();
        });
    })

    //检查功能权限, 无权限则退出系统
    function checkFunc(func){
        if(func == 2){//警员权限
            alert("警员无此功能权限");
            window.location.href = 'login.html';
        }
    }
    //识别结果统计
    function analyse(){
        var cameraList = $('#camera').combobox('getValues');
        var cameraListString = JSON.stringify(cameraList);
        var startTime = $('#startTime').datetimebox('getValue');
        var endTime = $('#endTime').datetimebox('getValue');
//console.log(cameraList, startTime, endTime);
        if(cameraList.length === 0 ){
            alert("请选择摄像头");
            return;
        }
        if(!startTime || startTime.trim() === ''){
            alert("请选择开始时间");
            return;
        }
        if(!endTime || endTime.trim() === ''){
            alert("请选择结束时间");
            return;
        }
        var startDate = new Date(startTime);
        var endDate = new Date(endTime);
        if (startDate >= endDate) {
            alert('开始时间必须早于结束时间！');
            return;
        }
        $.ajax({
            url: "result/analyse",
            type: "POST",
            data: {
                cameraList:cameraListString,
                startTime:startTime,
                endTime:endTime
            },
            success: function(response) {
                response= JSON.parse(response);
                console.log(response);
                dayBarChart(new Date(startTime), response[0]);
                cameraBarChart(response[1],response[2]);
                pieChart(response[3]);
//console.log(response);
                var text= "无头盔骑手数："+( response[3][1])+"; 总骑手数："+(response[3][0]+response[3][1]);
                $('#outputBox').val(text);

            },
            error: function(xhr, status, error) {
                alert("请求失败：" + status + " " + error);
            }
        });
    }


    //绘制直方图
    /**
     * 绘制动态柱状图
     * @param {Date} date - 起始日期
     * @param {number[]} dataList - 每日数据数组
     */
    function dayBarChart(date, dataList) {
        const ctx = document.getElementById('dayBarChart');
        if (!ctx) {
            console.error('Canvas元素未找到！');
            return;
        }

// 限制最多显示100个数据点
        const maxBars = 100;
        const displayData = dataList.slice(0, maxBars);

// 生成日期标签 (从起始日期开始按天递增)
        const dateLabels = [];
        for (let i = 0; i < displayData.length; i++) {
            const currentDate = new Date(date);
            currentDate.setDate(date.getDate() + i);
            dateLabels.push(currentDate.toLocaleDateString('zh-CN')); // 中文日期格式
        }

// 如果已存在图表实例则先销毁
        if (ctx.chart) {
            ctx.chart.destroy();
        }

// 创建新图表
        ctx.chart = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: dateLabels,
                datasets: [{
                    data: displayData,
                    backgroundColor: generateBarColors(displayData.length),
                    borderColor: 'rgba(75, 192, 192, 1)',
                    borderWidth: 1
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: {
                        beginAtZero: true,
                        title: {
                            display: true,
                            text: '数值'
                        }
                    },
                    x: {
                        title: {
                            display: true,
                            text: '日期'
                        }
                    }
                },
                plugins: {
                    title: {
                        display: true,
                        text: '每日无头盔人数' // 图表标题
                    },
                    legend: {
                        display: false
                    }
                }
            }
        });


    }
    /**
     * 绘制动态柱状图
     * @param {number[]} cameraList - 摄像头列表
     * @param {number[]} dataList - 每个摄像头的数据
     */
    function cameraBarChart(cameraList, dataList) {
        const ctx = document.getElementById('cameraBarChart');
        if (!ctx) {
            console.error('Canvas元素未找到！');
            return;
        }

// 限制最多显示100个数据点
        const maxBars = 100;
        const displayLabel = cameraList.slice(0, maxBars);
        const displayData = dataList.slice(0, maxBars);
        console.log(displayLabel);
        console.log(displayData);

// 如果已存在图表实例则先销毁
        if (ctx.chart) {
            ctx.chart.destroy();
        }

// 创建新图表
        ctx.chart = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: displayLabel,
                datasets: [{
                    data: displayData,
                    backgroundColor: generateBarColors(displayData.length),
                    borderColor: 'rgba(75, 192, 192, 1)',
                    borderWidth: 1
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: {
                        beginAtZero: true,
                        title: {
                            display: true,
                            text: '数值'
                        }
                    },
                    x: {
                        title: {
                            display: true,
                            text: '摄像头'
                        }
                    }
                },
                plugins: {
                    title: {
                        display: true,
                        text: '摄像头对应无头盔人数' // 图表标题
                    },
                    legend: {
                        display: false
                    }
                }
            }
        });


    }
    // 生成柱状图颜色 (可根据需要修改)
    function generateBarColors(count) {
        const colors = [];
        const hueStep = 360 / count;
        for (let i = 0; i < count; i++) {
            colors.push(`hsla(${i * hueStep}, 70%, 60%, 0.7)`);
        }
        return colors;
    }
    //绘制饼状图
    function pieChart(dataList){
        const ctx = document.getElementById('pieChart');
// 如果已存在图表实例则先销毁
        if (ctx.chart) {
            ctx.chart.destroy();
        }
        ctx.chart = new Chart(ctx, {
            type: 'pie', // 设置为饼图类型
            data: {
                labels: ['有头盔', '无头盔' ],
                datasets: [{
                    data: dataList,
                    backgroundColor: [
                        'rgba(255, 206, 86, 0.7)',
                        'rgba(255, 99, 132, 0.7)',
                    ],
                    borderColor: [
                        'rgba(255, 206, 86, 1)',
                        'rgba(255, 99, 132, 1)',
                    ],
                    borderWidth: 1
                }]
            },
            options: {
                responsive: true, // 图表自动适应容器大小
                plugins: {
                    legend: {
                        position: 'right', // 图例位置
                    },
                    title: {
                        display: true,
                        text: '无头盔人数占比' // 图表标题
                    }
                }
            }
        });
    }
    //设置日期格式
    $.fn.datetimebox.defaults.formatter = function (date) {
        var y = date.getFullYear();
        var m = date.getMonth() + 1;
        m = m < 10? ('0' + m) : m;
        var d = date.getDate();
        d = d < 10? ('0' + d) : d;
        var h = date.getHours();
        h = h < 10? ('0' + h) : h;
        var min = date.getMinutes();
        min = min < 10? ('0' + min) : min;
        var s = date.getSeconds();
        s = s < 10? ('0' + s) : s;
        return y + '-' + m + '-' + d + ' ' + h + ':' + min + ':' + s;
    };

    $.fn.datetimebox.defaults.parser = function (s) {
        if (!s) return new Date();
        var t = s.split(' ');
        var d = t[0].split('-');
        var time = t[1].split(':');
        return new Date(d[0], parseInt(d[1]) - 1, d[2], time[0], time[1], time[2]);
    };
</script>

</html>